export default class IconUI {
  constructor() {
    // 保存当前tab页的域名，据此判断当前页面有没有开启过HideAd扩展
    this.host = "";
    this.disableIcon = "disable.png";
    this.enableIcon = "enable.png";
    this.disableTitle = "HideAd已关闭";
    this.enableTitle = "HideAd已开启";
  }

  // 切换隐藏广告扩展开关
  async toggleHideAdSwitch(tab) {
    // console.log({tab});

    const status = await this.getPageStatus(tab);
    // 如果没有开启，则开启，反之则关闭
    const action = [undefined, "off"].includes(status) ? "on" : "off";
    // console.log(`开启/关闭 屏幕页面广告扩展功能: action=${action} host=${this.host}`);

    this.doAction(tab.id, action);
  }

  // 初始化页面扩展图标状态
  async initPageStatus(tab) {
    const status = await this.getPageStatus(tab);
    this.switchIconStatus(status);
  }

  // 获取页面状态
  async getPageStatus(tab) {
    // 页面没加载完成之前,tab.url的值为空,而tab.pendingUrl是有值的
    const url = tab.url || tab.pendingUrl;
    this.host = url?.split("/")?.[2] || "";
    return await this.getStorage(this.host);
  }

  // 执行扩展行为
  doAction(tabId, action) {
    this.switchIconStatus(action);
    this.setStorage(this.host, action);
    this.sendMessage(tabId, action);
  }

  // 切换扩展图标状态
  switchIconStatus(status) {
    console.log("switchIconStatus", status);
    if (status === "on") {
      this.setIcon(this.enableIcon);
      this.setTitle(this.enableTitle);
    } else {
      this.setIcon(this.disableIcon);
      this.setTitle(this.disableTitle);
    }
  }

  // 设置扩展标题
  setTitle(title) {
    chrome.action.setTitle({
      title,
    });
  }

  // 设置扩展图标
  setIcon(path) {
    chrome.action.setIcon({
      path: {
        64: path,
      },
    });
  }

  // 扩展程序向打开的页面发消息
  sendMessage(tabId, action) {
    chrome.tabs.sendMessage(tabId, { action });
  }

  // 扩展向硬盘写入存储值
  setStorage(key, val) {
    // console.log("setStorage", { key, val });
    return chrome.storage.sync.set({ [key]: val });
  }

  // 扩展从硬盘读取设置值
  async getStorage(key) {
    // 调试用--读取所有的设置值
    // chrome.storage.sync.get((result)=>{
    //   console.log(result);
    // })
    const res = await chrome.storage.sync.get();
    return res[key];
  }
}
